package serviceImpl;

import com.google.common.base.Strings;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.log4j.Logger;
import service.WebSocketCallBack;
import util.CODE;
import util.Request;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by thinkjoy on 2017/6/28.
 */
public class WebSocketServiceImpl implements WebSocketCallBack{
    private static final Logger LOG=Logger.getLogger(WebSocketServiceImpl.class);
    public static final Map<String,WebSocketCallBack> websocketMap=new ConcurrentHashMap<>();
    private ChannelHandlerContext ctx;
    private String name;

    public WebSocketServiceImpl(ChannelHandlerContext ctx, String name) {
        this.ctx = ctx;
        this.name = name;
    }

    public static boolean register(String requestId,WebSocketCallBack callBack){
        if(Strings.isNullOrEmpty(requestId)|| websocketMap.containsKey(requestId)){
            return false;
        }
        websocketMap.put(requestId,callBack);
        return true;
    }

    public static boolean logout(String requestId){
        if(Strings.isNullOrEmpty(requestId)|| !websocketMap.containsKey(requestId)){
            return false;
        }
        websocketMap.remove(requestId);
        return true;
    }

    @Override
    public void send(Request request) throws Exception {
        if(this.ctx==null || this.ctx.isRemoved()){
            throw  new Exception("尚未握手成功，无法向客户端发送WebSocket消息");
        }
        this.ctx.channel().write(new TextWebSocketFrame(request.toJson()));
        this.ctx.flush();
    }

    /**
     * 通知所有机器 有人下线
     * @param requestId
     */
    public static void notifyDownline(String requestId){
        WebSocketServiceImpl.websocketMap.forEach((reqId, callBack) -> {
            Request serviceRequest=new Request();
            serviceRequest.setServiceId(CODE.downline.code);
            serviceRequest.setRequestId(requestId);
            try {
                callBack.send(serviceRequest);
            } catch (Exception e) {
                LOG.warn("回调发送消息给客户端异常",e);
            }
        });
    }

    public String getName() {
        return name;
    }
}
